from RestAPI.amazon.core import AWS
from RestAPI.core.ResponseData import DataNode
from RestAPI.core.APIExceptions import APIException
import time

class ProductAPI(AWS):
    """
    Wrapper for Amazaon Product 
    """
    host='http://webservices.amazon.com/onca/xml?'
    reserved=['Service','AWSAccessKeyId']
    namespace='{http://webservices.amazon.com/AWSECommerceService/2011-08-01}'
    service='AWSECommerceService'
    def __init__(self,locale='us'):
        """
        set up the locale 
        """
        super(self.__class__,self).__init__()
        # different host url for different locale
        if locale.lower() == 'us':
            self.host=['http://','ecs.amazonaws.com','/onca/xml?']
        elif locale.lower() == 'cn':
            self.host=['http://','webservices.amazon.cn','/onca/xml?']
        elif locale.lower() == 'de':
            self.host=['http://','ecs.amazonaws.de','/onca/xml?']
        self.requestContext['Service']='AWSECommerceService'
    def getQueryUrl(self,parameters={}):
        if 'Service' not in self.requestContext:
            if hasattr(self,'service'):
                self.setupParameters({'Service': self.service })
            else:
                raise RequestServiceNotKnown()
        if 'AWSAccessKeyId' not in self.requestContext:
            if hasattr(self,'AuthKey'):
                self.setupParameters({'AWSAccessKeyId':self.AuthKey})
            else:
                raise NoAWSAccessKeyId()
        if 'AssociateTag' not in self.requestContext:
            if hasattr(self,'AssociateTag'):
                self.setupParameters({'AssociateTag':self.AssociateTag})
            else:
                raise NoAssociateTag()
        timestamp=time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
        self.setupParameters({'Timestamp': timestamp})
        url=super(ProductAPI,self).getQueryUrl(parameters)
        signature=self.getSignature("GET\n%s\n/onca/xml\n%s" % (self.host[1],url))
        url+='&Signature='+signature
        return url
    def searchItem(self,parameters):
        self.clear()
        self.pageKey='ItemPage'
        self.pageSizeKey='TagsPerPage'
        self.setupParameters({'Operation':'ItemSearch'})
        try:
            root=self.sendRequest(parameters)
        except Exception as err:
            myerror=DataNode(err.message,'{http://ecs.amazonaws.com/doc/2005-10-05/}')
            print myerror.str()
            for e in myerror['Error']:
                raise APIException(self.__class__.__name__+e.Code.str(),None,e.Message.str())
        root.setNamespace(self.namespace)
        for error in root['Error']:
            raise APIException(self.__class__.__name__+error.Code.str(),None,error.Message.str())
        return root

#shortcuts
class BookSearch(ProductAPI):
    """
    Look up information about a book from amazon.
    """
    pass
    
class MusicSearch(ProductAPI):
    """
    Look up infomration about music from amazon.
    """
    pass
